import { useEffect } from 'react';
import { Table, Input, message, Tag } from 'antd';
import update from 'immutability-helper';
import React, { useCallback, useRef, useState } from 'react';
import { DndProvider, useDrag, useDrop } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { cloneDeep } from 'lodash';
import { EditOutlined } from '@ant-design/icons';

interface DraggableBodyRowProps extends React.HTMLAttributes<HTMLTableRowElement> {
  index: number;
  moveRow: (dragIndex: number, hoverIndex: number) => void;
}

const type = 'DraggableBodyRow';

const DraggableBodyRow = ({
  index,
  moveRow,
  className,
  style,
  ...restProps
}: DraggableBodyRowProps) => {
  const ref = useRef<HTMLTableRowElement>(null);
  const [{ isOver, dropClassName }, drop] = useDrop({
    accept: type,
    collect: (monitor: any) => {
      const { index: dragIndex } = monitor.getItem() || {};
      if (dragIndex === index) {
        return {};
      }
      return {
        isOver: monitor.isOver(),
        dropClassName: dragIndex < index ? ' drop-over-downward' : ' drop-over-upward',
      };
    },
    drop: (item: { index: number }) => {
      moveRow(item.index, index);
    },
  });
  const [, drag] = useDrag({
    type,
    item: { index },
    collect: (monitor: any) => ({
      isDragging: monitor.isDragging(),
    }),
  });
  drop(drag(ref));

  return (
    <tr
      ref={ref}
      className={`${className}${isOver ? dropClassName : ''}`}
      style={{ cursor: 'move', ...style }}
      {...restProps}
    />
  );
};

interface Props {
  changeActivity: (data: any) => void;
  activityData: any[];
  isRead: boolean;
}

const TableDnd: React.FC<Props> = ({ activityData, changeActivity, isRead }) => {
  const [data, setData] = useState<any>([]);
  const [dataBro, setDataBro] = useState<any>([]);
  const inputRef = useRef<any>(null);

  // useEffect(() => {
  // }, [data]);
  useEffect(() => {
    activityData.forEach((item: any) => {
      item.editable = false;
    });
    setData(activityData);
    setDataBro(activityData);
  }, [activityData]);

  const components = {
    body: {
      row: DraggableBodyRow,
    },
  };

  const moveRow = useCallback(
    (dragIndex: number, hoverIndex: number) => {
      const dragRow = data[dragIndex];
      setData(
        update(data, {
          $splice: [
            [dragIndex, 1],
            [hoverIndex, 0, dragRow],
          ],
        }),
      );
      setDataBro(
        update(data, {
          $splice: [
            [dragIndex, 1],
            [hoverIndex, 0, dragRow],
          ],
        }),
      );
      changeActivity(
        update(data, {
          $splice: [
            [dragIndex, 1],
            [hoverIndex, 0, dragRow],
          ],
        }),
      );
    },
    [data],
  );

  const handleDelete = (index: number) => {
    //删除
    const dataSis = cloneDeep(data);
    dataSis.splice(index, 1);
    setData(dataSis);
    setDataBro(dataSis);
    changeActivity(dataSis);
  };

  const toggleEdit = (curIndex: number, toIndex: number) => {
    const dataSis = cloneDeep(data);
    dataSis[curIndex].editable = false;
    dataSis[toIndex].editable = false;
    const temp = dataSis[curIndex];
    dataSis[curIndex] = dataSis[toIndex];
    dataSis[toIndex] = temp;
    setData(dataSis);
    changeActivity(dataSis);
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 90,
      render: (text: any, record: any, index: number) => (
        <>
          {record.editable ? (
            <Input
              defaultValue={index + 1}
              type={'number'}
              ref={inputRef}
              min={1}
              onChange={(e) => {
                console.log('onChangee', e.target.value);
              }}
              onBlur={(e) => {
                console.log('onBluree', e.target.value);
                console.log('onBluree', Number.isInteger(Number(e.target.value)));
                if (
                  e.target.value &&
                  Number.isInteger(Number(e.target.value)) &&
                  Number(e.target.value) > 0 &&
                  Number(e.target.value) < data.length + 1
                ) {
                  toggleEdit(index, Number(e.target.value) - 1);
                } else {
                  message.error('请输入正确的序号');
                  const dataSis = cloneDeep(data);
                  dataSis[index].editable = false;
                  setData(dataSis);
                }
              }}
            />
          ) : (
            <div
              style={{ cursor: 'pointer' }}
              onClick={() => {
                const dataSis = cloneDeep(data);
                dataSis[index].editable = true;
                setData(dataSis);
                setTimeout(() => {
                  inputRef.current!.focus();
                });
              }}
            >
              {index + 1}
              <EditOutlined />
            </div>
          )}
        </>
      ),
    },
    {
      title: '活动ID',
      dataIndex: 'activityId',
      key: 'activityId',
      width: 170,
      ellipsis: true,
      render: (text: any, record: any, index: number) => (
        <>
          {record.needGenAsynFile && [-4, 2].includes(record.needGenAsynFile) ? (
            <span style={{ color: '#c62d2e' }}>
              <Tag color={'red'} style={{ position: 'absolute', top: 0, left: 0 }}>
                打开卡包券
              </Tag>
            </span>
          ) : null}
          {record.activityId}
        </>
      ),
    },
    {
      title: '活动名称',
      dataIndex: 'activity',
      key: 'activity',
      width: 180,
      ellipsis: true,
    },
    {
      title: '活动有效期',
      dataIndex: 'activityStartTime',
      key: 'activityStartTime',
      width: 300,
      render: (text: any, record: any) => (
        <>
          {record.activityStartTime}-{record.activityEndTime}
        </>
      ),
    },
    {
      title: 'Rank Value-堂食',
      dataIndex: 'maxRankValue',
      key: 'maxRankValue',
      width: 140,
      ellipsis: true,
      render: (text: any, record: any) => <>{record.maxRankValueCPOS || '0'}</>,
    },
    {
      title: 'TC Mix%-堂食',
      dataIndex: 'maxTcMix',
      key: 'maxTcMix',
      width: 130,
      ellipsis: true,
      render: (text: any, record: any) => (
        <>
          {record.maxTcMixCPOS ? Number(Number(record.maxTcMixCPOS) * 100).toFixed(4) + '%' : '0'}
        </>
      ),
    },
    {
      title: 'Rank Value-外送',
      dataIndex: 'maxRankValue',
      key: 'maxRankValue',
      width: 140,
      ellipsis: true,
      render: (text: any, record: any) => <>{record.maxRankValueDelivery || '0'}</>,
    },
    {
      title: 'TC Mix%-外送',
      dataIndex: 'maxTcMix',
      key: 'maxTcMix',
      width: 130,
      ellipsis: true,
      render: (text: any, record: any) => (
        <>
          {record.maxTcMixDelivery
            ? Number(Number(record.maxTcMixDelivery) * 100).toFixed(4) + '%'
            : '0'}
        </>
      ),
    },
  ];

  if (!isRead) {
    columns.push({
      title: '操作',
      key: 'operation',
      // @ts-ignore
      fixed: 'right',
      width: 100,
      align: 'center',
      render: (text: any, record: any, index: number) => (
        <div>
          {}
          <a
            onClick={() => {
              handleDelete(index);
            }}
          >
            删除
          </a>
        </div>
      ),
    });
  }

  return (
    // <div style={{ width: 650, marginTop: 16 }}>
    <div style={{ width: 'auto', marginTop: 16 }}>
      {/* @ts-ignore */}
      <DndProvider backend={HTML5Backend}>
        <Table
          // @ts-ignore
          columns={columns}
          dataSource={data}
          components={components}
          onRow={(_, index) => {
            const attr = {
              index,
              moveRow,
            };
            return attr as React.HTMLAttributes<any>;
          }}
          pagination={false}
          bordered
          scroll={{ x: 500, y: 300 }}
        />
      </DndProvider>
    </div>
  );
};

export default TableDnd;
